<template>
  <div>
    <el-switch
      v-model="isOpenDrag"
      active-text="开启拖拽"
      inactive-text="关闭拖拽">
    </el-switch>
    <el-button
      v-if="isOpenDrag"
      style="margin-left: 20px"
      type="success"
      size="mini"
      plain
      @click="save">保存</el-button>
    <el-button
      style="margin-left: 20px"
      type="danger"
      size="mini"
      plain
      @click="batchRemove">删除</el-button>
    <el-tree :data="data"
             :props="defaultProps"
             show-checkbox
             ref="menuTree"
             node-key="catId"
             :draggable="isOpenDrag"
             style="margin-top: 30px"
             :allow-drop="allowDrop"
             :default-expanded-keys="expandKey"
             @node-click="handleNodeClick"
             @node-drop="dragSuccess"
             :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
              type="text"
              size="mini"
              v-if="node.level <= 2"
              @click="() => append(data)">
            新增
          </el-button>
          <el-button
              type="text"
              size="mini"
              @click="() => update(data)">
            修改
          </el-button>
          <el-button
            type="text"
            size="mini"
            style="color: red"
            v-if="node.childNodes.length === 0"
            @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
        :title="title"
        :close-on-click-modal="false"
        :visible.sync="dialogVisible"
        width="30%">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      isOpenDrag: false,
      maxLevel: 0,
      title: '',
      category: {
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: '',
        productUnit: ''
      },
      dialogVisible: false,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      expandKey: [],
      updateNodes: [], // 修改的所有的节点的顺序集合
      pCid: []
    }
  },
  created () {
    this.getMenuTree()
  },
  methods: {
    batchRemove () {
      const deleteIds = this.$refs.menuTree.getCheckedNodes().map(node => node.catId)
      if (deleteIds.length === 0) {
        this.$message({
          message: '未选中需要删除的节点',
          type: 'warning'
        })
        return
      }
      this.$confirm(`是否删除当前选中的菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(deleteIds, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getMenuTree()
          }
        })
      })
    },
    save () {
      this.$http({
        url: this.$http.adornUrl('/product/category/update-sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            type: 'success',
            message: '拖拽完成!'
          })
          this.getMenuTree()
          this.expandKey = this.pCid
          // 重置拖拽缓存
          this.maxLevel = 0
          this.updateNodes = []
          this.pCid = []
        }
      })
    },
    dragSuccess (draggingNode, dropNode, dropType) {
      // 获取当前节点新的父节点id
      let pCid = 0
      let subNodes = []
      if (dropType === 'inner') {
        pCid = dropNode.data.catId
        subNodes = dropNode.childNodes // 设置当前子节点
      } else {
        pCid = dropNode.data.parentCid === undefined ? 0 : dropNode.data.parentCid
        subNodes = dropNode.parent.childNodes
      }
      // 添加到保存成功后需要展开的节点数组中
      this.pCid.push(pCid)
      // 获取当前节点拖动后的新顺序及其层级(包括子节点的层级都要更新)
      for (let i = 0; i < subNodes.length; i++) {
        if (subNodes[i].data.catId === draggingNode.data.catId) {
          let newCatLevel = draggingNode.level
          // 如果当前节点的层级发生变化
          if (subNodes[i].level !== draggingNode.level) {
            // 计算当前节点及其子节点变化后的新层级
            newCatLevel = subNodes[i].level
            // 修改子节点的层级
            this.updateChildNodeLevel(subNodes[i])
          }
          // 如果修改的时当前正在拖拽的节点, 重新修改其父级id
          this.updateNodes.push({catId: subNodes[i].data.catId, sort: i, parentCid: pCid, catLevel: newCatLevel})
        } else {
          this.updateNodes.push({catId: subNodes[i].data.catId, sort: i})
        }
      }
    },
    updateChildNodeLevel (node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.updateNodes.push({catId: node.childNodes[i].data.catId, catLevel: node.childNodes[i].level})
          this.updateChildNodeLevel(node.childNodes[i])
        }
      }
    },
    allowDrop (draggingNode, dropNode, type) {
      // 计算拖动节点的最大深度
      this.maxLevel = 0 // 重置最大层级
      this.countNodeLevel(draggingNode)
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1
      if (type === 'inner') {
        return deep + dropNode.level <= 3 // 拖进某个记得点中时, 保证拖动的当前节点树的深度 + 拖动到节点层级不大于3, 保证当前树不超过三层
      } else {
        return deep + dropNode.parent.level <= 3 // 如果只是拖动顺序, 不放入某个节点中, 就计算当前节点和目标节点的层级是否大于3即可
      }
    },
    countNodeLevel (node) {
      if (node.childNodes != null && node.childNodes.length > 0) { // 有子节点
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level
          }
          this.countNodeLevel(node.childNodes[i]) // 递归计算
        }
      }
    },
    submitData () {
      if (this.category.catId) {
        this.editCategory()
      } else {
        this.addCategory()
      }
    },
    editCategory () {
      let {catId, name, icon, productUnit} = this.category
      const request = {catId, name, icon, productUnit}
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'put',
        data: this.$http.adornData(request, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.getMenuTree()
          this.expandKey = [this.category.parentCid]
          this.dialogVisible = false
        }
      })
    },
    update (data) {
      this.dialogVisible = true
      this.title = '修改分类'

      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.category.name = data.category.name
          this.category.catId = data.category.catId
          this.category.icon = data.category.icon
          this.category.productUnit = data.category.productUnit
        }
      })
    },
    remove (node, data) {
      let ids = [data.catId]
      this.$confirm(`是否删除当前菜单${data.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getMenuTree()
            this.expandKey = [node.parent.data.catId]
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    addCategory () {
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          this.getMenuTree()
          this.expandKey = [this.category.parentCid]
          this.dialogVisible = false
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    append (data) {
      this.dialogVisible = true
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1
      this.title = '新增分类'

      // 清空输入
      this.category.catId = null
      this.category.name = ''
      this.category.icon = ''
      this.category.productUnit = ''
      this.category.sort = 0
      this.category.showStatus = 1
    },
    handleNodeClick (node) {

    },

    getMenuTree () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.data = data.data
        } else {
          this.data = []
        }
      })
    }
  }
}
</script>

<style>

</style>
